package com.myapp.blueslave;


import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class SlaveActivity extends Activity {

	private BluetoothAdapter mBluetoothAdapter = null;
	private static final int REQUEST_ENABLE_BT = 3;
	private BluetoothChatService mChatService = null;
	private ShowPatterns showPatterns;
	public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private boolean firstSignal = true;
    private ElectrodeDatabase db;
    private Timer extractValues,addTimer;
    //private ArrayAdapter<String> mConversationArrayAdapter;

    private StringBuffer mOutStringBuffer;
    private String mConnectedDeviceName = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(new ShowPatterns(this));
        extractValues = new Timer();
        //addTimer = new Timer();
        //addTimer.schedule(new AddValues(), 0, 66);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        db = new ElectrodeDatabase(this);
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        showPatterns = new ShowPatterns(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_slave, menu);
        return true;
    }

    @Override
    public void onStart() {
        super.onStart();

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        } else {
            if (mChatService == null) setupChat();
        }
    }
    
    @Override
    public synchronized void onResume() {
        super.onResume();

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
              mChatService.start();
            }
        }
    }
    
    private void setupChat(){
    	mChatService = new BluetoothChatService(this, mHandler);
    	//mOutStringBuffer = new StringBuffer("");
    }
    
    @Override
    public synchronized void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mChatService != null) mChatService.stop();
    }
    
    /*private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                display(readMessage);
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
    
    private void ensureDiscoverable() {
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }*/
    
    public void display(String str){
    	//showPatterns.showValue(str);
    	Toast.makeText(this, "Received : "+str, Toast.LENGTH_SHORT).show();
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                setupChat();
            } else {
                // User did not enable Bluetooth or an error occured
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                //mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                Log.i("SlaveActivity", "IN HANDLER, BEFORE CALL OF display() METHOD: "+readMessage);
                Log.d("SlaveActivity", "message,"+readMessage+",end");
                if(readMessage.length() != 0)
                	db.addData(new Data(Long.parseLong(readMessage)));
                if(firstSignal){
                	extractValues.schedule(new ExtractValues(), 3000, 3000);
                	firstSignal = false;
                }
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
    
    public void showToast(String str){
    	Toast.makeText(this, str, Toast.LENGTH_LONG).show();
    }
    
    public void extractValue(){
    	while(true){
    		try{
    			Thread.sleep(3000);
    		}catch(Exception e){}
    		Log.d("Algorithm", "Average : "+db.getFirstTenAvg());
    	}
    }
    
    public class ExtractValues extends TimerTask{

		@Override
		public void run() {
			//showText("Average : "+db.getFirstTenAvg());
			Log.d("Algorithm", "Average : "+db.getFirstTenAvg());
			showPatterns.setString(db.getFirstTenAvg());
			//showToast("Average : "+db.getFirstTenAvg());
			Message msg = mHandler.obtainMessage(0);
			Bundle bundle = new Bundle();
	        bundle.putString(SlaveActivity.TOAST, "Average : "+db.getFirstTenAvg());
	        msg.setData(bundle);
			mDialogHandler.sendMessage(msg);
			db.deleteAllData();
		}
	}
    
    /*public class AddValues extends TimerTask{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			long num = (long)(1000*Math.random());
			db.addData(new Data(num));
			Log.d("Algorithm", "AddValue "+num);
		}
	}*/
    
    private Handler mDialogHandler = new Handler(){
    	public void handleMessage(android.os.Message msg) {
    		if(msg.what == 0)
    			Toast.makeText(getApplicationContext(), msg.getData().getString(SlaveActivity.TOAST), Toast.LENGTH_SHORT).show();
    	}
    };
    
    /*public void finish(){
    	
    }*/
    
    public void onBackPressed(){
    	if(extractValues != null){
    		extractValues.cancel();
    		extractValues.purge();
    	}
    	//addTimer.cancel();
    	//addTimer.purge();
    	finish();
    }
}
